package findBestTradeTiming.java;

import java.util.Arrays;

public class findBestTradeTiming {
    public static void main(String[] args) {
        int[] prices = new int[]{3,2,6,5,0,3};
        System.out.println(maxProfit(prices));
    }

    public static int maxProfit2(int prices[]) {
        // 最低价格
        int minprice = Integer.MAX_VALUE;
        // 最高收益
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

    /**
     * 动态规划
     * @param prices
     * @return
     */
    public static int maxProfit(int prices[]) {
        if (prices == null || prices.length == 0) return 0;
        int length = prices.length;
        // dp[i][0]代表第i天持有股票的最大收益
        // dp[i][1]代表第i天不持有股票的最大收益
        int[][] dp = new int[length][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0],-prices[i]);
            dp[i][1] = Math.max(dp[i][0] + prices[i],dp[i-1][1]);
            System.out.println(dp[i][0] + "<->" + dp[i][1]);
        }
        return dp[prices.length-1][1];
    }

}
